package com.socket.nio.nio.chat.example2.server.handler;

import com.socket.nio.nio.chat.example2.message.GroupCreateRequestMessage;
import com.socket.nio.nio.chat.example2.message.GroupCreateResponseMessage;
import com.socket.nio.nio.chat.example2.server.session.Group;
import com.socket.nio.nio.chat.example2.server.session.GroupSession;
import com.socket.nio.nio.chat.example2.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

/**
 * 群组创建
 *
 * @author Hexudong
 * @date 2025/5/18
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage message) throws Exception {
    String groupName = message.getGroupName();
    Set<String> members = message.getMembers();

    //群管理器
    GroupSession groupSession = GroupSessionFactory.getGroupSession();
    Group group = groupSession.createGroup(groupName, members);
    System.out.println("group : " + group);

    GroupCreateResponseMessage responseMessage;
    // 返回null表示成功创建群聊
    if (group == null) {
      // 成功消息
      responseMessage = GroupCreateResponseMessage.builder()
          .success(true)
          .reason(groupName + " 创建成功")
          .build();
      ctx.writeAndFlush(responseMessage);
      // 发送拉群消息
      List<Channel> membersChannels = groupSession.getMembersChannel(groupName);
      for (Channel membersChannel : membersChannels) {
        membersChannel.writeAndFlush(GroupCreateResponseMessage.builder()
            .success(true)
            .reason("您已被拉入 [" + groupName + "]群")
            .build());
      }
    } else {
      responseMessage = GroupCreateResponseMessage.builder()
          .success(false)
          .reason(groupName + " 已经存在")
          .build();
      ctx.writeAndFlush(responseMessage);
    }
  }
}
